package com.shadow.study.excel.service;

import com.alibaba.excel.EasyExcelFactory;
import com.baomidou.mybatisplus.extension.service.IService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.shadow.study.excel.entity.ExcelEntity;
import com.shadow.study.excel.exception.MyExcelException;
import com.shadow.study.excel.in.ExcelListener;
import com.shadow.study.excel.in.ExcelVO;
import com.shadow.study.excel.mapper.ExcelMapper;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;

import java.io.IOException;
import java.io.InputStream;

@Slf4j
@Service
public class ExcelService extends ServiceImpl<ExcelMapper, ExcelEntity> implements IService<ExcelEntity> {

    /** 数据导出Excel默认名称. **/
    private static final String EXCEL_NAME_DEFAULT       = "数据导出列表";

    /** 数据导出Excel的sheet默认名称. **/
    private static final String EXCEL_SHEET_NAME_DEFAULT = "Sheet1";

    public String importData(final MultipartFile excel, final String sheetName) {
        try (InputStream inputStream = excel.getInputStream()) {

            ExcelListener listener = new ExcelListener(this, 10);
            EasyExcelFactory.read(inputStream, ExcelVO.class, listener)
                    .sheet(StringUtils.defaultIfBlank(sheetName, EXCEL_SHEET_NAME_DEFAULT))
                    .doRead();
        } catch (MyExcelException e) {
            return e.getMsg();
        } catch (IOException e) {
            return e.getMessage();
        }
        return null;
    }
}
